﻿using System;
using System.Text;
using HttpCodeLib;
using QQLogin.Properties;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;

namespace QQLogin
{
    public class QQLoginHelper
    {
        private readonly static HttpHelpers helper = new HttpHelpers();
        private readonly static XJHTTP xjHttp = new XJHTTP();
        private HttpItems item;
        private static string hsJs = Resources.hs;
        private static string pwdJs = Resources.pwd;
        private static string cdataJs = Resources.cdata;
        private static string tokenJs = Resources.token;
        private string res = string.Empty;
        private string cookies = string.Empty;
        private string url = string.Empty;
        private string ver = string.Empty;
        private string pt_login_sig = string.Empty;
        private string rnd = string.Empty;
        private string cap_cd = string.Empty;
        private string verifysession = string.Empty;
        private string sess = string.Empty;
        private string vsig = string.Empty;
        private string websig = string.Empty;
        private string cdata = string.Empty;
        private string abc = string.Empty;
        private string qq = string.Empty;
        private string pass = string.Empty;

        private string userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.170 Safari/537.36";

        public QQLoginHelper(string qq, string pass)
        {
            this.qq = qq;
            this.pass = pass;
        }

        public bool IsNeedCode(ref string code)
        {
            url = "https://xui.ptlogin2.qq.com/cgi-bin/xlogin?appid=715030901&daid=73&pt_no_auth=1&s_url=http%3A%2F%2Fqun.qq.com%2F";
            item = new HttpItems
            {
                URL = url,
                Cookie = cookies
            };
            res = helper.GetHtml(item, ref cookies).Html;
            ver = xjHttp.GetMidHtml(res, "ver/", "/");
            pt_login_sig = GetCookie(cookies, "pt_login_sig");
            url = $"https://ssl.ptlogin2.qq.com/check?regmaster=&pt_tea=2&pt_vcode=1&uin={qq}&appid=715030901&js_ver={ver}&js_type=1&login_sig={pt_login_sig}&u1=http%3A%2F%2Fqun.qq.com%2F&r={xjHttp.GetTimeByJs()}&pt_uistyle=40";
            item = new HttpItems
            {
                URL = url
            };
            res = helper.GetHtml(item, ref cookies).Html;
            var datas = res.Replace("ptui_checkVC(", "").Replace(");", "").Replace("'", "").Split(',');
            var needCode = datas[0];
            code = datas[1];
            verifysession = GetCookie(cookies, "ptvfsession");
            if (needCode == "0") return false;
            var ua = xjHttp.GetString2Base64(userAgent);
            url = $"https://ssl.captcha.qq.com/cap_union_prehandle?aid=715030901&asig=&captype=&protocol=https&clientype=2&disturblevel=&apptype=2&curenv=inner&ua={ua}&uid={qq}&cap_cd={code}&lang=2052&callback=_aq_682949&subsid=1";
            item = new HttpItems
            {
                URL = url,
                UserAgent = userAgent,
                Cookie = cookies
            };
            res = helper.GetHtml(item, ref cookies).Html;
            var json = res.Replace("_aq_682949(", "").Replace(")", "");
            var obj = JObject.Parse(json);
            var sess = obj["sess"].ToString();
            var sid = obj["sid"].ToString();
            var createIframeStart = xjHttp.GetTimeByJs();
            rnd = GetRandom(6);

            //url = $"https://ssl.captcha.qq.com/cap_union_new_show?aid=715030901&asig=&captype=&protocol=https&clientype=2&disturblevel=&apptype=2&curenv=inner&ua={ua}&sess={sess}&theme=&sid={sid}&noBorder=noborder&fb=1&forcestyle=undefined&subsid=2&showtype=embed&uid={qq}&cap_cd={code}&lang=2052&rnd={rnd}&TCapIframeLoadTime=15&prehandleLoadTime=147&createIframeStart={createIframeStart}";
            //item = new HttpItems
            //{
            //    URL = url,
            //    UserAgent = userAgent,
            //    Cookie = cookies
            //};
            //res = helper.GetHtml(item, ref cookies).Html;
            //var vsig = new Regex("tt=\"(.*?)\"").Match(res).Groups[1].Value;
            //var websig = new Regex("&websig=(.*?)\"").Match(res).Groups[1].Value;
            //var id = new Regex("captcha.qq.com/hycdn_1_(.*?)_0").Match(res).Groups[1].Value;
            //var imageUrl = $"https://hy.captcha.qq.com/hycdn_1_{id}_0";
            
            url = $"https://ssl.captcha.qq.com/cap_union_new_getsig?aid=715030901&asig=&captype=&protocol=https&clientype=2&disturblevel=&apptype=2&curenv=inner&ua={ua}&sess={sess}&theme=&sid=6579737199730806058&noBorder=noborder&fb=1&forcestyle=undefined&subsid=6&showtype=embed&uid={qq}&cap_cd={code}&lang=2052&rnd={rnd}&TCapIframeLoadTime=15&prehandleLoadTime=147&createIframeStart={createIframeStart}&rand=0.8607387946009999";
            item = new HttpItems
            {
                URL = url,
                UserAgent = userAgent,
                Cookie = cookies
            };
            res = helper.GetHtml(item, ref cookies).Html;
            obj = JObject.Parse(res);
            var picUrl = obj["cdnPic1"].ToString();
            var m= obj["chlg"]["M"].ToString();
            var ans = obj["chlg"]["ans"].ToString();
            var randstr = obj["chlg"]["randstr"].ToString();
            var initX = obj["initx"].ToString();
            var initY = obj["inity"].ToString();
            var vsig = obj["vsig"].ToString();
            return true;
        }

        public string Login(string code)
        {
            var v1 = "0";
            if (!code.Contains("!"))
            {
                v1 = "1";
                var collect = xjHttp.RunJsMethod(hsJs, "", "Hs");
                var postData = $"aid=715030901&asig=&captype=&protocol=https&clientype=2&disturblevel=&apptype=2&curenv=inner&sess={sess}&theme=&noBorder=noborder&fb=1&showtype=embed&uid={qq}&cap_cd={cap_cd}&lang=2052&rnd={rnd}&subcapclass=0&vsig={vsig}&cdata={cdata}&{abc}={collect}&websig={websig}&ans={code}&tlg=1";
                url = $"https://ssl.captcha.qq.com/cap_union_new_verify?random={xjHttp.GetTimeByJs()}";
                item = new HttpItems
                {
                    URL = url,
                    Method = "POST",
                    Postdata = postData,
                    Cookie = cookies
                };
                res = helper.GetHtml(item, ref cookies).Html;
                if (res.Contains("验证失败"))
                {
                    return "验证失败";
                }
                var obj = JObject.Parse(res);
                code = obj["randstr"].ToString();
                verifysession = obj["ticket"].ToString();
            }
            var token = xjHttp.RunJsMethod(tokenJs, "", "token");
            pass = xjHttp.RunJsMethod(pwdJs, $"'{pass}','{qq}','{code}'", "getpwd");
            url = $"https://ssl.ptlogin2.qq.com/login?u={qq}&verifycode={code}&pt_vcode_v1={v1}&pt_verifysession_v1={verifysession}&p={pass}&pt_randsalt=2&pt_jstoken={token}&u1=http%3A%2F%2Fqun.qq.com%2F&ptredirect=1&h=1&t=1&g=1&from_ui=1&ptlang=2052&action=4-5-{xjHttp.GetTimeByJs()}&js_ver={ver}&js_type=1&login_sig={pt_login_sig}&pt_uistyle=40&aid=715030901&daid=73&has_onekey=1&";
            item = new HttpItems
            {
                URL = url,
                Cookie = cookies
            };
            res = helper.GetHtml(item, ref cookies).Html;
            var msg = res.Replace("'", "").Split(',')[4];
            return msg;
        }

        public static string GetCookie(string cookie, string key)
        {
            var value = xjHttp.GetMidHtml(cookie + ";", $"{key}=", ";");
            return value;
        }

        private static char[] constant = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        public static string GetRandom(int Length)
        {
            StringBuilder newRandom = new StringBuilder(10);
            Random rd = new Random();
            for (int i = 0; i < Length; i++)
            {
                newRandom.Append(constant[rd.Next(10)]);
            }
            return newRandom.ToString();
        }

        public bool Check()
        {
            var item = new HttpItems
            {
                URL = "http://film.qq.com/weixin/topic/binding.html",
                Cookie = cookies
            };
            helper.GetHtml(item, ref cookies);
            item = new HttpItems
            {
                URL = $"http://vip.video.qq.com/fcgi-bin/comm_cgi?name=bindphone&otype=json&cmd=1&_t=5&sid=&code=&act=&from=aphone&_=1531927781625&callback=Zepto1531927781560",
                Cookie = cookies,
                Referer = "http://film.qq.com/weixin/topic/binding.html",
                UserAgent = "Mozilla/5.0 (Linux; Android 6.0; PRO 6 Build/MRA58K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043221 Safari/537.36 V1_AND_SQ_7.0.0_676_YYB_D QQ/7.0.0.3135 NetType/WIFI WebP/0.3.0 Pixel/1080"
            };
            var html = helper.GetHtml(item, ref cookies).Html.Replace("Zepto1531927781560(", "").Replace(");", "");
            var obj = JObject.Parse(html);
            if (obj["result"]["code"].ToString() == "0") return false;
            //Zepto1531927781560({"act":0,"bind_time":"1531926876","phone":"17070296015","result":{"code":0,"msg":"OK"}});已经绑定
            return true;
        }

        public bool GetCode(string phone, out string msg)
        {
            var item = new HttpItems
            {
                URL = $"http://vip.video.qq.com/fcgi-bin/comm_cgi?name=bindphone&otype=json&cmd=16&_t=7&sid={phone}&code=&act=&from=aphone&_=1531920037671&callback=Zepto1531920028005",
                Cookie = cookies,
                Referer = "http://film.qq.com/weixin/topic/binding.html",
                UserAgent = "Mozilla/5.0 (Linux; Android 6.0; PRO 6 Build/MRA58K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043221 Safari/537.36 V1_AND_SQ_7.0.0_676_YYB_D QQ/7.0.0.3135 NetType/WIFI WebP/0.3.0 Pixel/1080"
            };
            var html = helper.GetHtml(item, ref cookies).Html.Replace("Zepto1531920028005(", "").Replace(");", "");
            var obj = JObject.Parse(html);
            var ret = obj["ret"].ToString();
            if (ret != "0")
            {
                msg = "验证码发送失败";
                return false;
            }
            if (obj["bind_user_flag"].ToString() == "1")
            {
                msg = "手机已经绑定过";
                return false;
            }
            item = new HttpItems
            {
                URL = $"http://vip.video.qq.com/fcgi-bin/comm_cgi?name=bindphone&otype=json&cmd=1&_t=1&sid={phone}&code=&act=&from=aphone&_={xjHttp.GetTimeByJs()}&callback=Zepto1531925979241",
                Cookie = cookies,
                Referer = "http://film.qq.com/weixin/topic/binding.html",
                UserAgent = "Mozilla/5.0 (Linux; Android 6.0; PRO 6 Build/MRA58K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043221 Safari/537.36 V1_AND_SQ_7.0.0_676_YYB_D QQ/7.0.0.3135 NetType/WIFI WebP/0.3.0 Pixel/1080"
            };
            html = helper.GetHtml(item, ref cookies).Html.Replace("Zepto1531925979241(", "").Replace(");", "");
            //{"act":0,"allow_bind":0,"result":{"code":0,"msg":"OK"}}
            msg = html;
            return true;
        }

        public bool Bind(string phone, string code, out string msg)
        {
            var item = new HttpItems
            {
                URL = $"http://vip.video.qq.com/fcgi-bin/comm_cgi?name=bindphone&otype=json&cmd=1&_t=0&sid={phone}&code={code}&act=act&from=aphone&_={xjHttp.GetTimeByJs()}&callback=Zepto1531920028007",
                Cookie = cookies,
                Referer = "http://film.qq.com/weixin/topic/binding.html",
                UserAgent = "Mozilla/5.0 (Linux; Android 6.0; PRO 6 Build/MRA58K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043221 Safari/537.36 V1_AND_SQ_7.0.0_676_YYB_D QQ/7.0.0.3135 NetType/WIFI WebP/0.3.0 Pixel/1080"
            };
            var html = helper.GetHtml(item, ref cookies).Html.Replace("Zepto1531920028007(", "").Replace(");", "");
            var obj = JObject.Parse(html);
            if (obj["result"]["code"].ToString() != "0")
            {
                msg = obj["result"]["msg"].ToString();
                return false;
            }
            if (obj["match"].ToString() == "0")
            {
                msg = obj["result"]["msg"].ToString();
                return false;
            }
            msg = "绑定成功";
            return true;
        }
    }
}
